package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysAgentUser;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WechatUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户信息
 * 
 * @author ruoyi
 */

@RestController
@RequestMapping("/system/api")
public class SysApiController extends BaseController
{
    private String prefix = "system/api";

    @Autowired
    private ISysUserService userService;

    
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IReInfoService reInfoService;

    @Autowired
    private SysPasswordService passwordService;


    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IReAccountService reAccountService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private IRePhotoService rePhotoService;

    @Autowired
    private ISysNoticeService noticeService;
    @Value(value = "${app.appId}")
    private  String appId;
    @Value(value = "${app.secret}")
    private  String secret;
    @Value(value = "${app.url}")
    private  String url;
    /**
     * 手机端中介登录
     */
    @ApiOperation("手机端中介用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "code", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "signature", value = "签名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "rawData", value = "签名", dataType = "String", dataTypeClass = String.class)
    })
    @Log(title = "手机端中介用户登录", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping ("/wxLogin")
    @ResponseBody
    public AjaxResult wxLogin( String code,String signature,String rawData) throws JsonProcessingException {

        logger.info("code================================"+code);
        logger.info("signature================================"+signature);
        logger.info("rawData================================"+rawData);
        logger.info("appId=============================="+appId);
        logger.info("secret=============================="+secret);
        logger.info("url=============================="+url);
        // 1.接收小程序发送的code
        // 2.开发者服务器 登录凭证校验接口 appi + appsecret + code
        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(code,appId,secret,url);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        String sessionKey = SessionKeyOpenId.getString("session_key");
        logger.info("openid================================"+openid);
        logger.info("sessionKey================================"+sessionKey);
        String signature2 = DigestUtils.sha1Hex(rawData + sessionKey);
        logger.info("signature2================================"+signature2);
        if (!signature.equals(signature2)) {
            return AjaxResult.error("签名校验失败");
        }


      SysUser user=  userService.selectUserByOpenId(openid);

//        Map<Integer, SysUser> users = new LinkedHashMap<Integer, SysUser>();
//        ObjectMapper objectMapper = new ObjectMapper();

        logger.info("user===================="+user);
      if(user==null){
          user=new SysUser();

          return AjaxResult.register(user);

      }else {
//          String jsonStr = objectMapper.writeValueAsString(user);
          user.setOpenId(openid);
          user.setSessionKey(sessionKey);
          logger.info("user===================="+user);
          return AjaxResult.success(user);


      }


    }


    /**
     * 用户名密码登录
     */
    @ApiOperation("用户名密码登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "登录名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "String", dataTypeClass = String.class),

    })
    @Log(title = "用户名密码登录", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping ("/login")
    @ResponseBody
    public AjaxResult login( String username,String password){
        logger.info("username==================="+username);
        logger.info("password==================="+password);
        SysUser user=userService.selectUserByLoginName(username);
        logger.info("user==================="+user);
        if(user!=null){
            String mima=passwordService.encryptPassword(username, password, user.getSalt());
            logger.info("mima==================="+mima);
            if(mima.equals(user.getPassword())){
                return  AjaxResult.success("登录成功",user);
            }else {
                return  AjaxResult.error("密码错误");
            }
        }else {
            return  AjaxResult.error("密码错误");
        }


    }

    /**
     * 手机端中介用户注册保存用户
     */
    @ApiOperation("手机端中介用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "机构id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "userName", value = "真实名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "phonenumber", value = "用户手机", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "code", value = "code", dataType = "code", dataTypeClass = String.class)
    })
    @Log(title = "手机端中介用户注册", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping ("/agnetSave")
    @ResponseBody
    public AjaxResult agnetSave(@Validated SysAgentUser sysAgentUser)

    {

        logger.info("code==================================="+sysAgentUser.getCode());

        JSONObject SessionKeyOpenId = WechatUtil.getSessionKeyOrOpenId(sysAgentUser.getCode(),appId,secret,url);
        // 3.接收微信接口服务 获取返回的参数
        String openid = SessionKeyOpenId.getString("openid");
        logger.info("openid==================================="+openid);
        String sessionKey = SessionKeyOpenId.getString("session_key");
//       String phone= WechatUtil.getPhoneNumber(sysAgentUser.getCode(),appId,secret);

        SysUser user=new SysUser();
        user.setDeptId(sysAgentUser.getDeptId());
        user.setLoginName(sysAgentUser.getPhonenumber());
        user.setUserName(sysAgentUser.getUserName());
        user.setPhonenumber(sysAgentUser.getPhonenumber());
        user.setSex(sysAgentUser.getSex());
        user.setCreateBy(sysAgentUser.getPhonenumber());
       user.setOpenId(openid);
        user.setSessionKey(sessionKey);
        if (!userService.checkLoginNameUnique(user))
        {
            return AjaxResult.failconfirm("新增用户'" + sysAgentUser.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return AjaxResult.failconfirm("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }


        user.setPost("1");
        //user.setRating("0");
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        userService.insertUser(user);

        return AjaxResult.success(user);
    }


    /**
     * 手机端中介用户注册
     */
    @ApiOperation("手机端银行用户注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "机构id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "userName", value = "真实名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "loginName", value = "登录名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "phonenumber", value = "用户手机", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "sex", value = "性别", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "code", value = "code", dataType = "String", dataTypeClass = String.class)
    })
    @Log(title = "手机端银行用户注册", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping("/bankSave")
    @ResponseBody
    public AjaxResult bankSave(@Validated SysAgentUser sysAgentUser)

    {


        SysUser user=new SysUser();
        user.setDeptId(sysAgentUser.getDeptId());
        user.setLoginName(sysAgentUser.getLoginName());
        user.setUserName(sysAgentUser.getUserName());
        user.setPhonenumber(sysAgentUser.getPhonenumber());
        user.setSex(sysAgentUser.getSex());

        if (!userService.checkLoginNameUnique(user))
        {
            return AjaxResult.error("新增用户'" + sysAgentUser.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return AjaxResult.error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }

        SysUser user1=new SysUser();
        user.setPost("0");
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(getLoginName());

        return toAjax(userService.insertUser(user));
    }


    /**
     * 获取所有网点
     */
    @ApiOperation("获取所有网点")
    @Log(title = "获取所有网点", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping("/getNetworks")
    @ResponseBody
    public AjaxResult getNetworks(){
        return  AjaxResult.success(deptService.selectDeptThree())  ;
    }

    /**
     * 手机端中介用户注册保存用户
     */
    @ApiOperation("预约开户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyName", value = "企业名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "address", value = "企业地址", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "reDate", value = "预约日期", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "contactsTel", value = "联系人电话", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "contactsName", value = "联系人姓名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "orgId", value = "预约银行", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "userId", value = "userId", dataType = "String", dataTypeClass = String.class)

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping("/reInfoSave")
    @ResponseBody
    public AjaxResult reInfoSave(String  companyName,String address,String reDate,String contactsTel,String contactsName,String orgId,String userId) throws ParseException {

        logger.info("=============开户信息保存接口");
        logger.info("=============companyName"+companyName);
        logger.info("=============address"+address);
        logger.info("=============reDate"+reDate);
        logger.info("=============contactsTel"+contactsTel);
        logger.info("=============contactsName"+contactsName);
        logger.info("=============orgId"+orgId);
        logger.info("=============userId"+userId);

        SysUser user=null;
        SysDept dept=null;
        SysDept bank=null;
//        if(reInfoApi.getPhone().isEmpty()){
//            return AjaxResult.error("未获取到登录人的手机号码");
//        }else {
//             user=userService.selectUserByPhoneNumber(reInfoApi.getPhone());
//        }

        if(!userId.isEmpty()){

            user=userService.selectUserById(Long.valueOf(userId));
            dept=deptService.selectDeptById(user.getDeptId());
        }else {
            return AjaxResult.error("用户Id为空");
        }

        if(!orgId.isEmpty()){

            bank=deptService.selectDeptById(Long.valueOf(orgId));
        }else {
            return AjaxResult.error("预约银行为空");
        }

        if(companyName.isEmpty()){

            return AjaxResult.error("公司名称为空");
        }

        if(address.isEmpty()){

            return AjaxResult.error("公司地址为空");
        }

        if(reDate.isEmpty()){

            return AjaxResult.error("预约时间为空");
        }

        if(contactsTel.isEmpty()){

            return AjaxResult.error("联系人电话为空");
        }
        if(contactsName.isEmpty()){

            return AjaxResult.error("联系人姓名为空");
        }
        if(orgId.isEmpty()){

            return AjaxResult.error("银行网点为空");
        }

        ReInfo reInfo=new ReInfo();

        reInfo.setCompanyName(companyName);
        reInfo.setAddress(address);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
        Date date = sdf.parse(reDate); // 进行转换
        reInfo.setReDate(date);
        reInfo.setContactsTel(contactsTel);
        reInfo.setContactsName(contactsName);
        reInfo.setOrgId(bank.getDeptId());
        reInfo.setOrgName(bank.getDeptName());
        reInfo.setCashState("0");
        reInfo.setCreateBy(user.getLoginName());
        reInfo.setAccountState("0");
        reInfo.setPhone(user.getPhonenumber());
        if(user!=null){
            reInfo.setUserId(Long.valueOf(userId));
            reInfo.setUserName(user.getUserName());
            reInfo.setDeptName(dept.getDeptName());
            reInfo.setOpenId(user.getOpenId());
        }

        //yyyyMMddHHmmss
        Date now = new Date();
        String dateStamp = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(now);
        long timestamp = System.currentTimeMillis();
        Random random = new Random();
        int randomNum = random.nextInt(1000);
        String renumber="YQGD"+ timestamp  + randomNum;
        reInfo.setReNumber(renumber);
        reInfoService.insertReInfo(reInfo);

        return AjaxResult.success("保存成功",reInfo.getId());
    }


    /**
     * 手机端中介用户注册保存用户
     */
    @ApiOperation("预约开户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyName", value = "企业名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "address", value = "企业地址", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "reDate", value = "预约日期", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "contactsTel", value = "联系人电话", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "contactsName", value = "联系人姓名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "orgId", value = "预约银行", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userId", value = "userId", dataType = "String", dataTypeClass = String.class)

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping(value = "/companySave",headers="content-type=multipart/form-data")
    @ResponseBody
    public AjaxResult companySave(@RequestPart("file")MultipartFile[] file,ReInfoApi reInfoApi)  {
        SysUser user=null;
        SysDept dept=null;
        SysDept bank=null;
//        if(reInfoApi.getPhone().isEmpty()){
//            return AjaxResult.error("未获取到登录人的手机号码");
//        }else {
//             user=userService.selectUserByPhoneNumber(reInfoApi.getPhone());
//        }


        Date now = new Date();
        String dateStamp = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(now);
        String[] avatar=new String[file.length];
        for(int i=0;i<file.length;i++){
            try {
                if (!file[i].isEmpty()) {
                    avatar[i] = FileUploadUtils.upload(serverConfig.getUrl() +RuoYiConfig.getProfile()+"/"+dateStamp, file[i], MimeTypeUtils.IMAGE_EXTENSION);

                }else {
                    return AjaxResult.error("未获取到上传的图片");
                }

            } catch (Exception e) {
                logger.error("上传图片失败！", e);
                return AjaxResult.error(e.getMessage());
            }
        }
        String paths=StringUtils.join(avatar,",");

        if(!reInfoApi.getUserId().isEmpty()){

            user=userService.selectUserById(Long.valueOf(reInfoApi.getUserId()));
            dept=deptService.selectDeptById(user.getDeptId());
        }else {
            return AjaxResult.success("用户Id为空");
        }

        if(!reInfoApi.getOrgId().isEmpty()){


            bank=deptService.selectDeptById(Long.valueOf(reInfoApi.getOrgId()));
        }else {
            return AjaxResult.success("预约银行为空");
        }

        ReInfo reInfo=new ReInfo();

        reInfo.setCompanyName(reInfoApi.getCompanyName());
        reInfo.setAddress(reInfoApi.getAddress());
        reInfo.setReDate(reInfoApi.getReDate());
        reInfo.setContactsTel(reInfoApi.getContactsTel());
        reInfo.setContactsName(reInfoApi.getContactsName());
        reInfo.setOrgId(bank.getDeptId());
        reInfo.setOrgName(bank.getDeptName());
        reInfo.setCashState("0");
        reInfo.setCreateBy(reInfoApi.getLoginName());
        reInfo.setAccountState("0");
        reInfo.setPhone(reInfoApi.getPhone());
        if(user!=null){
            reInfo.setUserId(Long.valueOf(reInfoApi.getUserId()));
            reInfo.setUserName(user.getUserName());
            reInfo.setDeptName(dept.getDeptName());
            reInfo.setOpenId(user.getOpenId());
        }

        //yyyyMMddHHmmss

        reInfo.setReNumber(dateStamp);
        reInfoService.insertReInfo(reInfo);

        return AjaxResult.success("保存成功"+reInfo);
    }

    /**
     * 通用上传请求（单个）
     */
    @ApiOperation("图片上传")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "name", value = "图片名称", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "reinfoId", value = "开户信息ID", dataType = "String", dataTypeClass = String.class)

    })
    @PostMapping(value = "/upload",headers="content-type=multipart/form-data")
    @ResponseBody
    public AjaxResult uploadFile(@RequestPart("file")MultipartFile file,String name,String reinfoId) throws Exception
    {
        logger.info("=============开户附件保存接口");
        logger.info("name======================"+name);
        logger.info("reinfoId======================"+reinfoId);
        logger.info("file======================"+file);
        Date now = new Date();
        String dateStamp = new java.text.SimpleDateFormat("yyyyMMddHHmmss").format(now);
        try
        {
            // 上传文件路径
            String filePath = RuoYiConfig.getProfile()+"/"+dateStamp;
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            RePhoto rePhoto=new RePhoto();
            rePhoto.setName(name);
            rePhoto.setPath(url);
            rePhoto.setReinfoId(Long.valueOf(reinfoId));
            ReInfo reInfo=reInfoService.selectReInfoById(Long.valueOf(reinfoId));

           rePhotoService.insertRePhoto(rePhoto);

            Map<String, String> map=new HashMap<>();
            map.put("bankName", reInfo.getOrgName());
            map.put("reNumber", reInfo.getReNumber());
            map.put("reDate", reInfo.getReDate().toString());
            return AjaxResult.success(map);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 中介下拉框
     */
    @ApiOperation("中介下拉框")
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping( value = "/getAgencys")
    @ResponseBody
    public AjaxResult getAgencys()
    {
        List<SysDept> deptList=new ArrayList<SysDept>();
        deptList=deptService.selectDeptListByPid(Long.valueOf("110"));
        if(deptList!=null&& deptList.size()>0) {
            return AjaxResult.success("查询成功",deptList);
        }else {
            return AjaxResult.error();
        }

    }

    /**
     * 分行下拉框
     */
    @ApiOperation("分行下拉框")
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping( value = "/oneBank")
    @ResponseBody
    public AjaxResult oneBank()
    {
      List<SysDept> deptList=new ArrayList<SysDept>();
      deptList=deptService.selectDeptListByPid(Long.valueOf("100"));
      if(deptList!=null&& deptList.size()>0) {
          return AjaxResult.success("查询成功",deptList);
      }else {
          return AjaxResult.error();
      }

    }

    /**
     * 支行或者营业厅行下拉框
     */
    @ApiOperation("支行或营业厅下拉框")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "parentId", value = "父ID", dataType = "Long", dataTypeClass = Long.class)

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping( value = "/childBank")
    @ResponseBody
    public AjaxResult childBank(Long parentId)
    {
        List<SysDept> deptList=new ArrayList<SysDept>();
        deptList=deptService.selectDeptListByPid(parentId);
        if(deptList!=null&& deptList.size()>0) {
            return AjaxResult.success("查询成功",deptList);
        }else {
            return AjaxResult.error();
        }

    }

    /**
     * 中介账户状态列表接口
     */
    @ApiOperation("中介账户状态列表接口")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "userId", value = "userId", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "accountState", value = "账户状态", dataType = "String", dataTypeClass = String.class)

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping ("/orderList")
    @ResponseBody
    public AjaxResult orderList(Integer userId,String accountState)
    {

        logger.info("=============中介账户状态列表接口");
        logger.info("userId============="+userId);
        logger.info("accountState============="+accountState);
        if(userId==null){
            return AjaxResult.error("登录用Id未获取");
        }
        if(accountState.isEmpty()){
            return AjaxResult.error("accountState未获取");
        }
        ReInfo reInfo=new ReInfo();
        reInfo.setAccountState(accountState);
        reInfo.setUserId(Long.valueOf(userId));
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        List<ReInfo> list1=new ArrayList<ReInfo>();
        if(list!=null&& !list.isEmpty()) {
            for(ReInfo info :list){
                String name=dictDataService.selectDictLabel("accountType",reInfo.getAccountType());

                info.setAccountName(name);
                list1.add(info);
            }
            return AjaxResult.success("查询成功",list1);
        }else {
            return AjaxResult.error("查询失败，未查询到数据");
        }

    }



        /**
         * 个人开户积分列表
         */
        @ApiOperation("个人开户积分列表")
        @ApiImplicitParams({

                @ApiImplicitParam(name = "userId", value = "userId", dataType = "String", dataTypeClass = String.class)

        })
        @RepeatSubmit(interval = 2000, message = "请求过于频繁")
        @GetMapping ("/openScoringList")
        @ResponseBody
        public AjaxResult openScoringList(Integer userId)
        {

            logger.info("=============个人开户积分列表接口");
            logger.info("userId============="+userId);
            if(userId==null){
                return AjaxResult.error("登录用Id未获取");
            }
            ReInfo reInfo=new ReInfo();
            reInfo.setAccountCheck("1");
            reInfo.setAccountState("3");
            reInfo.setCashState("0");
            reInfo.setUserId(Long.valueOf(userId));
            List<ReInfo> list=new ArrayList<ReInfo>();
          list = reInfoService.selectReInfoList(reInfo);

            if(list!=null&& !list.isEmpty()) {
                return AjaxResult.success("查询成功",list);
            }else {
                return AjaxResult.success("查询失败，未查询到结果",list);
            }

        }

    /**
     * 个人开户积分列表
     */
    @ApiOperation("个人开户积分合计")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "userId", value = "userId", dataType = "String", dataTypeClass = String.class)

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping("/openScoringListCount")
    @ResponseBody
    public AjaxResult openScoringListCount(Integer  userId)
    {
        logger.info("=============个人开户积分合计接口");
        logger.info("userId===================="+userId);
        if(userId==null){
            return  AjaxResult.error("登录用Id未获取");
        }
        ReInfo reInfo=new ReInfo();
        reInfo.setAccountCheck("1");
        reInfo.setAccountState("3");
        reInfo.setCashState("0");
        reInfo.setUserId(Long.valueOf(userId));
        List<ReInfo> list=new ArrayList<ReInfo>();
       list = reInfoService.selectReInfoList(reInfo);
         long sums=0;
        if(list!=null&& !list.isEmpty()) {
            for(ReInfo info :list){
                if(info.getCashState().equals("0")&& info.getBonus()!=null){
                    sums=sums+info.getBonus();
                }
            }
            return AjaxResult.success("查询成功",(int) sums);
        }else {
            return AjaxResult.success("查询失败，未查询到结果",0);
        }


    }

    /**
     * 个人开户积分提现
     */
    @ApiOperation("个人开户积分提现")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "ids", value = "ids", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "userId", value = "userId", dataType = "String", dataTypeClass = String.class)

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping( value = "/businessCash")
    @ResponseBody
    public AjaxResult businessCash(String ids,Integer  userId)
    {
        logger.info("=============个人开户积分提现接口");
        logger.info("ids============="+ids);
        if(userId==null){
            return AjaxResult.error("未获取登录用户ID");
        }
        if(ids==null||ids.isEmpty()){
            return AjaxResult.error("请选择要提现的记录");
        }
        SysUser user=userService.selectUserById(Long.valueOf(userId));
        String[] accountIds = Convert.toStrArray(ids);
        for (String id : accountIds)
        {
            ReInfo reInfo=reInfoService.selectReInfoById(Long.valueOf(id));
            reInfo.setCashState("1");
            reInfo.setCashDate(new Date());
            reInfo.setCashUser(user.getUserName());
            reInfo.setCashkUserId(user.getUserId());
            reInfoService.updateReInfo(reInfo);

        }
        return  AjaxResult.success(accountIds.length);

    }

    /**
     * 个人分销积分积分列表
     */
    @ApiOperation("个人分销积分积分列表")
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "userId", value = "userId", dataType = "String", dataTypeClass = String.class)

    })
    @GetMapping( value = "/accountScoringList")
    @ResponseBody
    public AjaxResult accountScoringList(Integer  userId)
    {
        if(userId==null){
            return  AjaxResult.error("登录用Id未获取");
        }

        ReAccount reAccount=new ReAccount();
        reAccount.setUserId(Long.valueOf(userId));
        reAccount.setCashState("0");
        List<ReAccount> list=new ArrayList<ReAccount>();
     list = reAccountService.selectReAccountList(reAccount);
        if(list!=null&& !list.isEmpty()) {
            return AjaxResult.success("查询成功",list);
        }else {
            return AjaxResult.success("查询失败，未查询到结果",list);
        }

    }

    /**
     * 个人开户积分列表
     */
    @ApiOperation("分销开户积分合计")
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "userId", value = "userId", dataType = "String", dataTypeClass = String.class)

    })
    @GetMapping( value = "/accountScoringListCount")
    @ResponseBody
    public AjaxResult accountScoringListCount(Integer  userId)
    {
        if(userId==null){
            return  AjaxResult.error("登录用Id未获取");
        }
        ReAccount reAccount=new ReAccount();
        reAccount.setUserId(Long.valueOf(userId));
        reAccount.setCashState("0");
        List<ReAccount> list=new ArrayList<ReAccount>();
        list = reAccountService.selectReAccountList(reAccount);
        long sums=0;
        if(list!=null&& !list.isEmpty()) {
            for(ReAccount info :list){
                if(info.getCashState().equals("0")&& info.getBonus()!=null){
                    sums=sums+info.getBonus();
                }
            }
            return AjaxResult.success("查询成功",(int) sums);
        }else {
            return AjaxResult.success("查询失败,未查询到结果",0);
        }


    }



    /**
     * 开户进度查询
     */
    @ApiOperation("开户状态查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "reNumber", value = "预约编号", dataType = "String", dataTypeClass = String.class)
    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping( value = "/openState")
    @ResponseBody
    public AjaxResult openState(String reNumber)
    {

        ReInfo reInfo = reInfoService.selectReInfoByreNumber(reNumber);

        if(reInfo!=null) {
            String name=dictDataService.selectDictLabel("account_state",reInfo.getAccountState());
            return AjaxResult.success("查询成功",name);
        }else {
            return AjaxResult.success("未查询到相关信息","");
        }

    }


    /**
     * 银行端接洽
     */
    @ApiOperation("银行端接洽")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "accountType", value = "账户性质", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "accountState", value = "账户状态", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "refinoId", value = "预约记录ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "userId", value = "银行端登录用户Id", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "acceptDate", value = "接洽日期", dataType = "String", dataTypeClass = String.class),

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping("/bankArrange")
    @ResponseBody
    public AjaxResult bankArrange(@RequestBody Arrange arrange) throws ParseException {

        logger.info("=============银行端接洽接口");
//        logger.info("=============acceptDate===="+acceptDate);
        logger.info("=============accountType======"+arrange.getAccountType());
        logger.info("=============accountState===="+arrange.getAccountState());
        logger.info("=============remark==="+arrange.getRemark());
        logger.info("=============refinoId==="+arrange.getRefinoId());
        logger.info("=============userId===="+arrange.getUserId());
        logger.info("=============userId===="+arrange.getAcceptDate());

        SysUser user=null;
        ReInfo reInfo=null;

        if(arrange.getAcceptDate().isEmpty()){
            return AjaxResult.error("接洽日期为空");
        }

        if(arrange.getUserId()!=null){

            user=userService.selectUserById(Long.valueOf(arrange.getUserId()));

        }else {
            return AjaxResult.error("用户Id为空");
        }

        if(arrange.getRefinoId()!=null){

            reInfo=reInfoService.selectReInfoById(Long.valueOf(arrange.getRefinoId()));
        }else {
            return AjaxResult.error("预约银行为空");
        }
//
//        if(acceptDate.isEmpty()){
//
//            return AjaxResult.error("接洽日期为空");
//        }

        if(arrange.getAccountType().isEmpty()){

            return AjaxResult.error("账户性质为空");
        }

        if(arrange.getAccountState().isEmpty()){

            return AjaxResult.error("接洽结果为空");
        }


 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
        Date date=sdf.parse(arrange.getAcceptDate());
        reInfo.setAcceptDate(date);
        reInfo.setReception(user.getUserName());
        reInfo.setReceptionId(user.getUserId());
        reInfo.setAccountType(arrange.getAccountType());
        reInfo.setAccountState(arrange.getAccountState());
        reInfo.setRemark(arrange.getRemark());

        reInfoService.updateReInfo(reInfo);

        return AjaxResult.success("保存成功",reInfo);
    }


    /**
     * 银行端开户成功
     */
    @ApiOperation("银行端开户成功")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "successDate", value = "开户日期", dataType = "Date", dataTypeClass = Date.class),
            @ApiImplicitParam(name = "accountState", value = "账户状态", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "accountNo", value = "账号", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "remark", value = "备注", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "refinoId", value = "预约记录ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "userId", value = "银行端登录用户Id", dataType = "Long", dataTypeClass = Long.class),
    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @PostMapping("/bankSuccess")
    @ResponseBody
    public AjaxResult bankSuccess(@RequestBody BankSucces bankSucces) throws ParseException {

        logger.info("=============银行端开户成功接口");
        logger.info("=============successDate===="+bankSucces.getSuccessDate());
        logger.info("=============accountState===="+bankSucces.getAccountState());
        logger.info("=============accountNo===="+bankSucces.getAccountNo());
        logger.info("=============remark==="+bankSucces.getRemark());
        logger.info("=============refinoId==="+bankSucces.getRefinoId());
        logger.info("=============userId===="+bankSucces.getUserId());


        SysUser user=null;
        ReInfo reInfo=null;

//        if(reInfoApi.getPhone().isEmpty()){
//            return AjaxResult.error("未获取到登录人的手机号码");
//        }else {
//             user=userService.selectUserByPhoneNumber(reInfoApi.getPhone());
//        }

        if(bankSucces.getUserId()!=null){

            user=userService.selectUserById(Long.valueOf(bankSucces.getUserId()));

        }else {
            return AjaxResult.error("用户Id为空");
        }

        if(bankSucces.getRefinoId()!=null){

            reInfo=reInfoService.selectReInfoById(Long.valueOf(bankSucces.getRefinoId()));
        }else {
            return AjaxResult.error("预约银行为空");
        }

        if(bankSucces.getSuccessDate().isEmpty()){

            return AjaxResult.error("开户日期为空");
        }



        if(bankSucces.getAccountState().isEmpty()){

            return AjaxResult.error("开户状态为空");
        }
        if(bankSucces.getAccountNo().isEmpty()){

            return AjaxResult.error("账号为空");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 定义日期格式
        Date date=sdf.parse(bankSucces.getSuccessDate());
        reInfo.setSuccessDate(date);
        reInfo.setConfirm(user.getUserName());
        reInfo.setConfirmId(user.getUserId());
        reInfo.setAccountState(bankSucces.getAccountState());
        reInfo.setAccountState(bankSucces.getAccountNo());
        reInfo.setRemark(bankSucces.getRemark());

        reInfoService.updateReInfo(reInfo);

        return AjaxResult.success("保存成功",reInfo);
    }



    /**
     * 银行账户状态列表接口
     */
    @ApiOperation("银行账户状态列表接口")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "userId", value = "userId", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "accountState", value = "账户状态", dataType = "String", dataTypeClass = String.class)

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping ("/infoList")
    @ResponseBody
    public AjaxResult infoList(Integer userId,String accountState)
    {

        logger.info("=============银行账户状态列表接口");
        logger.info("userId============="+userId);
        logger.info("accountState============="+accountState);
        if(userId==null){
            return AjaxResult.error("登录用Id未获取");
        }
        if(accountState.isEmpty()){
            return AjaxResult.error("accountState未获取");
        }
        SysUser user=userService.selectUserById(Long.valueOf(userId));
        ReInfo reInfo=new ReInfo();
        reInfo.setOrgId(user.getDeptId());
        reInfo.setAccountState(accountState);
        List<ReInfo> list = reInfoService.selectReInfoList(reInfo);
        List<ReInfo> list1=new ArrayList<ReInfo>();
        if(list!=null&& !list.isEmpty()) {
            for(ReInfo info :list){
                String name=dictDataService.selectDictLabel("accountType",reInfo.getAccountType());

                List<RePhoto> rePhotos=rePhotoService.selectRePhotoListByReinfoId(info.getId());
                info.setAccountName(name);
                info.setPhotos(rePhotos);
                list1.add(info);
            }
            return AjaxResult.success("查询成功",list1);
        }else {
            return AjaxResult.error("查询失败，未查询到数据");
        }

    }


    /**
     * 根据ID获取机构信息
     */
    @ApiOperation("根据ID获取机构信息")
    @ApiImplicitParams({

            @ApiImplicitParam(name = "deptId", value = "机构ID", dataType = "Integer", dataTypeClass = Integer.class),

    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping ("/getDeptById")
    @ResponseBody
    public AjaxResult getDeptById(Integer deptId )
    {

        logger.info("=============根据ID获取机构信息");
        logger.info("deptId============="+deptId);

        if(deptId==null){
            return AjaxResult.error("机构Id未获取");
        }

        SysDept dept=deptService.selectDeptById(Long.valueOf(deptId));
        logger.info("dept============="+dept);
        if(dept!=null) {

            return AjaxResult.success("查询成功",dept);
        }else {
            return AjaxResult.error("查询失败，未查询到数据");
        }

    }


    /**
     * 通知公告
     */
    @ApiOperation("通知公告")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "noticeType", value = "类型", dataType = "String", dataTypeClass = Integer.class)
    })
    @RepeatSubmit(interval = 2000, message = "请求过于频繁")
    @GetMapping ("/noticeList")
    @ResponseBody
    public AjaxResult noticeList(String noticeType)
    {

        logger.info("=============通知公告列表接口");
        logger.info("noticeType============="+noticeType);


        if(noticeType.isEmpty()){
            return AjaxResult.error("noticeType不能为空");
        }
        SysNotice sysNotice=new SysNotice();
        sysNotice.setNoticeType(noticeType);
        List<SysNotice> list=noticeService.selectNoticeList(sysNotice);

        if(list!=null&& !list.isEmpty()) {

            return AjaxResult.success("查询成功",list);
        }else {
            return AjaxResult.error("查询失败，未查询到数据");
        }

    }
}

